package com.data.permission.transf;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.KeyedPooledObjectFactory;
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
import org.apache.thrift.protocol.TProtocol;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @包名称 com.thrift.distributed.process
 * @类描述 <pre></pre>
 * @作者 zhangbo
 * @创建时间 2019/9/19
 * @版本 1.00
 * @修改记录 <pre>
 *     版本           修改人         修改日期         修改内容描述
 *     -----------------------------------------------------------
 *     1.00           Lenovo        2019/9/19
 *     -----------------------------------------------------------
 * </pre>
 */
@Getter
@Slf4j
@Service
public class ClientConnectPool {

    @Value("${MaxTotal:200}")
    private int maxTotal;
    @Value("${MaxIdle:50}")
    private int maxIdle;
    @Value("${MinIdle:10}")
    private int minIdle;
    @Value("${MaxWaitMillis:5000}")
    private long maxWaitMillis;

    private GenericKeyedObjectPool<ServiceInfo,TProtocol> genericKeyedObjectPool;

    /**
     * 初始化池
     */
    public void init() {
        GenericKeyedObjectPoolConfig<TProtocol> config = new GenericKeyedObjectPoolConfig<>();
        //最大连接数
        config.setMaxTotal(maxTotal);
        //最大空闲连接数
        config.setMaxIdlePerKey(maxIdle);
        //最小空闲连接
        config.setMinIdlePerKey(minIdle);
        //最大等待时间
        config.setMaxWaitMillis(maxWaitMillis);

        config.setTestWhileIdle(true);
        config.setTestOnCreate(true);
        config.setTestOnBorrow(true);
        config.setTestOnReturn(true);

        KeyedPooledObjectFactory keyedPooledObjectFactory = new ClientFactory();
        genericKeyedObjectPool = new GenericKeyedObjectPool<ServiceInfo, TProtocol>(keyedPooledObjectFactory,config);
    }

    /**
     * 获取对象
     * @param serviceInfo
     * @return
     */
    public TProtocol getProtocol(ServiceInfo serviceInfo) {
        if(null == genericKeyedObjectPool) {
            init();
        }
        try {
            return genericKeyedObjectPool.borrowObject(serviceInfo);
        } catch (Exception e) {
            log.error("从池中获取对象失败：{}",e);
        }
        return null;
    }

    /**
     * 归还对象
     * @param serviceInfo
     * @param protocol
     */
    public void returnProtocol(ServiceInfo serviceInfo,TProtocol protocol) {
        if(null != protocol) {
            genericKeyedObjectPool.returnObject(serviceInfo,protocol);
        }
    }


}
